package com.jsnkj.basic.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.recyclerview.widget.LinearLayoutManager
import com.jsnkj.basic.R
import com.jsnkj.basic.activity.MainActivity
import com.jsnkj.basic.activity.TextActivity
import com.jsnkj.basic.activity.WithdrawActivity
import com.jsnkj.basic.adapter.MessageAdapter
import com.jsnkj.basic.advertisement.AdvertisementManager
import com.jsnkj.basic.bean.ReadPacketMessageBean
import com.jsnkj.basic.config.RewardsConfig
import com.jsnkj.basic.config.SpConfig
import com.jsnkj.basic.databinding.FragmentRedPacketBinding
import com.jsnkj.basic.dialog.OpenRedPacketDialog
import com.jsnkj.basic.mvvm.BaseMVVMActivity
import com.jsnkj.basic.mvvm.BaseMVVMFragment
import com.jsnkj.basic.util.ErrorResultUtil
import com.jsnkj.basic.util.RewardsUtil
import com.jsnkj.basic.util.SharePreferencesUtil
import com.hzhj.openads.domain.HJAdError
import com.hzhj.openads.domain.HJNativeAdData
import com.hzhj.openads.listener.HJOnAdsSdkRewardListener
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlin.random.Random


class RedPacketFragment : BaseMVVMFragment<FragmentRedPacketBinding, RedPacketViewModel>() {

    companion object {
        fun newInstance() = RedPacketFragment()
    }

    override val layoutId: Int
        get() = R.layout.fragment_red_packet

    val min = 1500


    private val bannerHandler = Handler(Looper.getMainLooper())
    private var bannerRunnable: Runnable? = null
    var sendMessageTime: Long = 0L

    private var msgAdapter: MessageAdapter? = null
    private var itemBeans: ArrayList<ReadPacketMessageBean> = ArrayList()

    //打开红包弹窗
    var openDialog: OpenRedPacketDialog? = null

    var positionIndex = -1

    //列表选中下标
    var redPacketBean: ReadPacketMessageBean? = null


    override fun initView(savedInstanceState: Bundle?) {

        var redName = SharePreferencesUtil.getInstance().getInt(SpConfig.RED_PACKET_NAME, 0)
        if (0 == redName) {
            // 1-100
            redName = 1 + Random.Default.nextInt(100)
            SharePreferencesUtil.getInstance().putInt(SpConfig.RED_PACKET_NAME, redName)
        }

        var redNumber = SharePreferencesUtil.getInstance().getInt(SpConfig.RED_PACKET_NUMBER, 0)
        if (0 == redNumber) {
            // 1500 - 3000
            redNumber = min + Random.Default.nextInt(min + 1)
            SharePreferencesUtil.getInstance().putInt(SpConfig.RED_PACKET_NUMBER, redNumber)
        }

        mVDB.txtTitle.text = "红包群$redName（$redNumber）"

        initRecyclerView()

        mVDB.txtWithdrawal.setOnClickListener {
            startActivity(requireActivity(), WithdrawActivity::class.java)
        }

        mVDB.txtTitle.setOnClickListener {
            if (com.jsnkj.basic.BuildConfig.DEBUG) {
                startActivity(requireActivity(), TextActivity::class.java)
            }
        }

        LiveEventBus.get<String>("readFragmentRefresh").observe(this) {
            com.jsnkj.basic.util.LogUtils.e("刷新用户信息")
            mVM.postAuthUserInfo()
        }
    }


    override fun bindEvent() {
        super.bindEvent()

        // 初始化 Runnable 对象
        bannerRunnable = object : Runnable {
            override fun run() {

                if (SpConfig.isError) {
                    bannerHandler.removeCallbacks(bannerRunnable!!);
                    return
                }

                val time = System.currentTimeMillis() / 1000
                if (sendMessageTime < 1L) {
                    sendMessageTime = time
                }

                val bean = ReadPacketMessageBean()
                bean.id = time.toString()

                bean.avatar = mVM.avatars[Random.Default.nextInt(mVM.avatars.size - 1)]
                bean.userName = mVM.usernames[Random.Default.nextInt(mVM.usernames.size - 1)]
                bean.sendMessageTime = time

//                LogUtils.e("每隔 3秒发送一次消息  time == $time  sendMessageTime == $sendMessageTime ")
                //每隔2条信息 发送一次红包
                if (time - sendMessageTime > 13 && sendMessageTime > 0) {
                    bean.messageType = 2
                    sendMessageTime = time

                    msgAdapter?.sendMessage(bean)
                    refreshListdata()
                } else {
                    if (msgAdapter!!.itemCount > 0 && msgAdapter?.getItemViewType(msgAdapter!!.itemCount - 1) == 2) {

                        //加载信息流
                        AdvertisementManager.loadHjNativeAds(requireActivity(),
                            object :
                                com.jsnkj.basic.adlistener.FeedAdsListener {
                                override fun onFeedLoadSuccess(dataList: MutableList<Any>?) {
                                    com.jsnkj.basic.burialpoint.BurialPointUtil.flowAdEvent("show")
                                    if(dataList!=null && dataList.size>0){
                                        var hjNativeAdData:HJNativeAdData = dataList.get(0) as HJNativeAdData;
                                        bean.messageType = 1
                                        bean.hjNativeAdData = hjNativeAdData
                                        msgAdapter?.sendMessage(bean)
                                        refreshListdata()
                                    }
                                }

                                override fun onFeedLoadFail(msg: String?) {
                                    com.jsnkj.basic.util.LogUtils.e("信息流广告记载失败")
                                }
                            },300)
                    } else {
                        bean.sendMessage =
                            mVM.messages[Random.Default.nextInt(mVM.messages.size - 1)]
                        bean.messageType = 0

                        msgAdapter?.sendMessage(bean)
                        refreshListdata()
                    }
                }
            }
        }

        // 开始定时器
        bannerHandler.postDelayed(bannerRunnable!!, SpConfig.RED_PACKET_TIME)

        mVM.errorResult.observe(this) {
            dismissDialog()

            if (SpConfig.HTTP_ERROR_CODE == it.code) {
                // 取消定时器，避免内存泄漏
                bannerHandler.removeCallbacks(bannerRunnable!!)
            }

            ErrorResultUtil.errorResultToast(requireActivity() as BaseMVVMActivity<*, *>, it)
        }

        mVM.postAdWardsReceiveResult.observe(this) {
            dismissDialog()
//            ToastUtils.show(it)
            com.jsnkj.basic.util.LogUtils.e("得到的奖励：$it")
            (requireActivity() as MainActivity).showResultDialog(RewardsConfig.goldMoney.toString())
            mVM.postAuthUserInfo()
        }


        mVM.postAdreWardsResult.observe(this) {
            dismissDialog()
            SharePreferencesUtil.getInstance().clearAdBeanList()
            redPacketBean?.sendMessageTime = 0
            msgAdapter?.updateMessage(redPacketBean)

            refreshListdata()

            RewardsConfig.goldMoney = it.coins
            postShowOpenDialog(positionIndex)
        }

        mVM.postLoginResult.observe(this) { user ->
            dismissDialog()

            com.jsnkj.basic.util.LogUtils.e("红包页，请求用户信息回调 $user")
            SharePreferencesUtil.getInstance().getUserBean()?.let {
                it.user = user
                SharePreferencesUtil.getInstance().putUserBean(it)
            }

            SharePreferencesUtil.getInstance().getUserBean()?.user?.withdrawable_coins?.let {
                mVDB.txtTopMoney.text = it.toString()
            }

            refreshListdata()
        }

        mVM.postAuthUserInfo()
    }


    fun refreshListdata() {
        mVDB.rvRedPacket.scrollToPosition(msgAdapter!!.itemCount - 1)

        // 取消定时器，避免内存泄漏
        bannerHandler.removeCallbacks(bannerRunnable!!)
        // 再次调用 postDelayed 来循环执行
        bannerHandler.postDelayed(bannerRunnable!!, SpConfig.RED_PACKET_TIME) // 3000 毫秒后再次执行
    }


    private fun initRecyclerView() {
        if (null == msgAdapter) {
            msgAdapter = MessageAdapter(
                requireActivity(), itemBeans, object : MessageAdapter.onItemClickListener {
                    override fun onItemCallBack(position: Int) {
                        positionIndex = position

                        //点击之后 就失效
                        itemBeans[position].sendMessageTime = 0
                        msgAdapter!!.notifyItemChanged(position)

                        redPacketBean = itemBeans[position]

                        showDialog()
                        mVM.postAdreWards()
                    }
                })
        }

        mVDB.rvRedPacket.apply {
            layoutManager =
                LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
            adapter = msgAdapter
        }
    }


    private var isInitFragment = false

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (!isInitFragment) {
            return
        }
        com.jsnkj.basic.util.LogUtils.e("setUserVisibleHint  是否可见： $isVisibleToUser")

        if (isVisibleToUser) {
            msgAdapter?.notifyDataSetChanged()
            refreshListdata()
            mVM.postAuthUserInfo()
        } else {
            // 取消定时器，避免内存泄漏
            bannerHandler.removeCallbacks(bannerRunnable!!);
        }

    }

    override fun onResume() {
        super.onResume()
        isInitFragment = true
        msgAdapter?.notifyDataSetChanged()
    }


    fun postShowOpenDialog(position: Int) {
        if (null == openDialog) {
            openDialog = OpenRedPacketDialog(
                requireActivity(), itemBeans[position],
                object : OpenRedPacketDialog.onItemClickListener {
                    override fun openItemClickListener() {

                        showLoadRewardVideo(itemBeans[position])
                    }

                    override fun closeCallBack() {
                        refreshListdata()

                        //弹出插屏广告
                        AdvertisementManager.showLoadInteraction(
                            requireActivity(),
                            SpConfig.AD_TIME
                        )

                        val currentTime = System.currentTimeMillis() / 1000
                        SharePreferencesUtil.getInstance()
                            .putLong(SpConfig.MAIN_OPEN_AD_TIME, currentTime)
                    }
                })
        }
        // 取消定时器，避免内存泄漏
        bannerHandler.removeCallbacks(bannerRunnable!!);
        openDialog?.showDialog()
    }


    var isFragmentReceiveReward = false
    fun showLoadRewardVideo(readPacketMessageBean: ReadPacketMessageBean) {
        com.jsnkj.basic.util.LogUtils.e("红包弹窗 -- 打开激励视频")

        SharePreferencesUtil.getInstance()
            .putBoolean(SpConfig.APP_LOCK_SCREEN, false)

        isFragmentReceiveReward = false

        AdvertisementManager.loadHjRewardAds(requireActivity(),object: HJOnAdsSdkRewardListener {
            override fun onVideoAdLoadSuccess(p0: String?) {
                //加载成功
                var option : HashMap<String,String> = hashMapOf(
                    "name" to "激励视频",
                    "position" to "redPacketFragment"
                )
                AdvertisementManager.showHJRewardAds(option);
            }

            override fun onVideoAdPlayEnd() {

            }

            override fun onVideoAdPlayStart() {

            }

            override fun onVideoAdClicked() {

            }

            override fun onVideoRewarded(p0: String?) {
                com.jsnkj.basic.util.LogUtils.e("激励视频奖励回调MainActivity,onVideoRewarded="+p0)
            }

            override fun onVideoAdClosed() {
                    com.jsnkj.basic.burialpoint.BurialPointUtil.playJlspAdEvent("show")

                    com.jsnkj.basic.util.LogUtils.e("激励视频  onClose()")
                    if (!isFragmentReceiveReward) {
                        mVM.postAdreWardsReceive()
                    }
                    SharePreferencesUtil.getInstance().putBoolean(SpConfig.APP_LOCK_SCREEN, true)
                    RewardsUtil.addAdTypeRewardGoldNumber(RewardsConfig.adStimulate)
            }

            override fun onVideoAdLoadError(p0: HJAdError?, p1: String?) {
                com.jsnkj.basic.util.LogUtils.e("激励视频加载失败回调onVideoAdLoadError="+p1)
                   com.jsnkj.basic.burialpoint.BurialPointUtil.playJlspAdEvent("fail")

                    SharePreferencesUtil.getInstance().putBoolean(SpConfig.APP_LOCK_SCREEN, true)

                    refreshListdata()
            }

            override fun onVideoAdPlayError(p0: HJAdError?, p1: String?) {
                com.jsnkj.basic.util.LogUtils.e("激励视频播放失败回调onVideoAdLoadError="+p1)
            }

        })

//        AdvertisementManager.loadRewardVideo(
//            requireActivity(),
//            "media_extra",
//            com.tb.mob.TbManager.Orientation.VIDEO_VERTICAL,
//            object : com.tb.mob.TbManager.RewardVideoLoadListener {
//                override fun getSDKID(p0: Int?, p1: String?) = Unit
//                override fun onClick() = Unit
//                override fun onClose() {
//                    BurialPointUtil.playJlspAdEvent("show")
//
//                    LogUtils.e("激励视频  onClose()")
//                    if (!isFragmentReceiveReward) {
//                        mVM.postAdreWardsReceive()
//                    }
//                    SharePreferencesUtil.getInstance().putBoolean(SpConfig.APP_LOCK_SCREEN, true)
//                }
//
//                override fun onRewardVideoCached(p0: RewardPosition?) = Unit
//                override fun onSkippedVideo() = Unit
//                override fun onFail(p0: String?) {
//                    //加载失败
//                    p0?.let { ToastUtils.show(p0) }
//                    BurialPointUtil.playJlspAdEvent("fail")
//
//                    SharePreferencesUtil.getInstance().putBoolean(SpConfig.APP_LOCK_SCREEN, true)
//
//                    refreshListdata()
//                }
//
//                override fun onExposure(p0: String?, p1: Position?) {
//                    LogUtils.e("加载激励视频 onExposure：值： ${p1?.ecpm}")
//                    positionBean = p1
//                }
//
//                override fun onRewardVerify() {
//                    isFragmentReceiveReward = false
//                    showDialog()
//                    mVM.postAdreWardsReceive()
//
//                    //激励视频触发激励（观看视频大于一定时长或者视频播放完毕）
//                    //如果使用服务器回调，可以将orderNo传给自己服务器来做后续的判断，也可以直接根据服务器回调直接发放奖励。
//                    LogUtils.e("加载激励视频 onRewardVerify： 值：${positionBean?.ecpm}")
//
//                    positionBean?.let {
//                        RewardsUtil.addGoldNumber(it.ecpm, RewardsConfig.adStimulate)
//                    }
//                }
//            })
    }

}